//
//  DR_FileDetailsSheet.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import SnapKit

class DR_FileDetailsSheet: UIView {
    
    var onDismiss: (() -> Void)?
    
    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    
    // 详情区域
    private let detailsContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 20
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.layer.masksToBounds = true
        return view
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "File Details"
        label.font = UIFont.systemFont(ofSize: 15, weight: .bold)
        label.textColor = .black
        return label
    }()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        let xmarkImage = UIImage(systemName: "xmark")
        button.setImage(xmarkImage, for: .normal)
        button.tintColor = .black
        return button
    }()
    
    private let lineView: UIView = {
        let v = UIView()
        v.backgroundColor = "#F5F5F5".toColor
        return v
    }()
    
    private let contentStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 12
        stackView.distribution = .fill
        return stackView
    }()
    
    private var detailViews: [UIView] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        addSubview(backgroundView)
        addSubview(detailsContainerView)
        
        detailsContainerView.addSubview(titleLabel)
        detailsContainerView.addSubview(closeButton)
        detailsContainerView.addSubview(lineView)
        detailsContainerView.addSubview(contentStackView)
    }
    
    private func setupConstraints() {
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 详情区域
        detailsContainerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(350)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(20)
        }
        
        closeButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-20)
            make.centerY.equalTo(titleLabel)
            make.width.height.equalTo(24)
        }
        
        lineView.snp.makeConstraints { make in
            make.trailing.leading.equalToSuperview().inset(15)
            make.top.equalToSuperview().offset(55)
            make.height.equalTo(1)
        }
        
        contentStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(15)
            make.top.equalTo(lineView.snp.bottom).offset(14)
        }
    }
    
    private func setupActions() {
        backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
        closeButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
    }
    
    @objc private func dismiss() {
        hide()
    }
    
    // MARK: - 配置文件详情
    func configure(with fileModel: DR_FileModel) {
        // 清除之前的视图
        detailViews.forEach { $0.removeFromSuperview() }
        detailViews.removeAll()
        
        // 获取文件修改时间
        let modificationDate = getFileModificationDate(fileURL: fileModel.fileURL) ?? fileModel.createDate
        
        // 格式化日期
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let lastViewString = dateFormatter.string(from: fileModel.createDate)
        let lastModifiedString = dateFormatter.string(from: modificationDate)
        
        // 获取文件扩展名（大写）
        let fileExtension = fileModel.fileURL.pathExtension.uppercased()
        
        let screenWidth = UIScreen.main.bounds.width
        let topCardWidth = (screenWidth - 45) / 2
        let bottomCardWidth = screenWidth - 30
        
        // 第一行：File Type 和 File Size（两列）
        let firstRow = UIStackView()
        firstRow.axis = .horizontal
        firstRow.distribution = .fill
        firstRow.spacing = 15
        
        let fileTypeView = createDetailView(label: "File Type", value: ".\(fileExtension)", width: topCardWidth, height: 66)
        let fileSizeView = createDetailView(label: "File Size", value: fileModel.fileSizeString, width: topCardWidth, height: 66)
        
        firstRow.addArrangedSubview(fileTypeView)
        firstRow.addArrangedSubview(fileSizeView)
        contentStackView.addArrangedSubview(firstRow)
        detailViews.append(contentsOf: [fileTypeView, fileSizeView])
        
        // 第二行：Last View 和 Last Modified（两列）
        let secondRow = UIStackView()
        secondRow.axis = .horizontal
        secondRow.distribution = .fill
        secondRow.spacing = 15
        
        let lastViewView = createDetailView(label: "Last View", value: lastViewString, width: topCardWidth, height: 66)
        let lastModifiedView = createDetailView(label: "Last Modified", value: lastModifiedString, width: topCardWidth, height: 66)
        
        secondRow.addArrangedSubview(lastViewView)
        secondRow.addArrangedSubview(lastModifiedView)
        contentStackView.addArrangedSubview(secondRow)
        detailViews.append(contentsOf: [lastViewView, lastModifiedView])
        
        // 第三行：Storage Path（全宽）
        let storagePathView = createDetailView(label: "Storage Path", value: fileModel.fileURL.path, width: bottomCardWidth, height: 83)
        contentStackView.addArrangedSubview(storagePathView)
        detailViews.append(storagePathView)
    }
    
    // MARK: - 创建详情项视图
    private func createDetailView(label: String, value: String, width: CGFloat, height: CGFloat) -> UIView {
        let containerView = UIView()
        containerView.backgroundColor = "#F6F7FF".toColor
        containerView.layer.cornerRadius = 16
        
        let labelLabel = UILabel()
        labelLabel.text = label
        labelLabel.font = UIFont.systemFont(ofSize: 12)
        labelLabel.textColor = "#8FA2C8".toColor
        
        let valueLabel = UILabel()
        valueLabel.text = value
        valueLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        valueLabel.textColor = .black
        valueLabel.numberOfLines = 0
        
        containerView.addSubview(labelLabel)
        containerView.addSubview(valueLabel)
        
        // 设置固定尺寸
        containerView.snp.makeConstraints { make in
            make.width.equalTo(width)
            make.height.equalTo(height)
        }
        
        labelLabel.snp.makeConstraints { make in
            make.leading.top.equalToSuperview().offset(12)
            make.trailing.equalToSuperview().offset(-12)
        }
        
        valueLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(12)
            make.top.equalTo(labelLabel.snp.bottom).offset(6)
            make.bottom.lessThanOrEqualToSuperview().offset(-12)
        }
        
        return containerView
    }
    
    // MARK: - 获取文件修改时间
    private func getFileModificationDate(fileURL: URL) -> Date? {
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
            return attributes[.modificationDate] as? Date
        } catch {
            return nil
        }
    }
    
    // MARK: - 显示和隐藏
    func show(in parentView: UIView) {
        parentView.addSubview(self)
        parentView.bringSubviewToFront(self)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: parentView.topAnchor),
            self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
        ])
        
        // 初始状态：背景透明，容器在底部外
        backgroundView.alpha = 0
        detailsContainerView.transform = CGAffineTransform(translationX: 0, y: 350)
        
        // 强制布局
        layoutIfNeeded()
        
        // 动画显示
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.backgroundView.alpha = 1
            self.detailsContainerView.transform = .identity
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.backgroundView.alpha = 0
            self.detailsContainerView.transform = CGAffineTransform(translationX: 0, y: 350)
        } completion: { _ in
            self.removeFromSuperview()
            self.onDismiss?()
        }
    }
}

